package com.li.network.lab_2;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class PingServer {
    public static void main(String[] args) {
        int port = 8086;
        try (DatagramSocket socket = new DatagramSocket(port)){
            while (true) {
                byte[] ping = new byte[1024];
                DatagramPacket pingPacket = new DatagramPacket(ping, ping.length);
                socket.receive(pingPacket);
                if (pingPacket.getData() != null) {
                    System.out.println("服务端接收：" + new String(ping, 0, pingPacket.getLength()));
                    if (Math.random() * 10 > 5) {
                        InetAddress clientAddress = pingPacket.getAddress();
                        int clientPort = pingPacket.getPort();
                        //回复pong
                        byte[] pong = new String(ping, 0, pingPacket.getLength()).replace('i', 'o').getBytes();
                        DatagramPacket pongPacket = new DatagramPacket(pong, pong.length, clientAddress, clientPort);
                        socket.send(pongPacket);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
